<template>
  <div>
    <h2>浏览历史记录</h2>
    <ul>
      <li v-for="item in historyItems" :key="item.id">
        <a :href="item.url" target="_blank">{{ item.title || item.url }}</a>
        <span>（访问时间：{{ formatTime(item.lastVisitTime) }}）</span>
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';

// 定义历史记录项的类型
interface HistoryItem {
  id: string;
  url?: string;
  title?: string;
  lastVisitTime?: number;
}

// 定义响应式的数据
const historyItems = ref<HistoryItem[]>([]);

// 获取浏览历史记录的函数
function fetchHistory() {
  const microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
  const oneWeekAgo = Date.now() - microsecondsPerWeek;

  // 使用 chrome.history.search 获取历史记录
  chrome.history.search(
    {
      text: '',
      startTime: oneWeekAgo,
      maxResults: 50
    },
    (results) => {
      historyItems.value = results;
    }
  );
}

// 格式化时间的函数
function formatTime(timestamp?: number): string {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString();
}

// 在组件挂载时调用 fetchHistory 函数
onMounted(() => {
  fetchHistory();
});
</script>
